package com.lc.hongtai.fragment;


import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.facebook.drawee.view.SimpleDraweeView;
import com.lc.hongtai.MyApplication;
import com.lc.hongtai.R;
import com.lc.hongtai.activity.AdvertisingActivity;
import com.lc.hongtai.activity.BorrowNextActivity;
import com.lc.hongtai.activity.InvestListActivity;
import com.lc.hongtai.activity.NewsActivity;
import com.lc.hongtai.activity.NewsInvestActivity;
import com.lc.hongtai.adapter.HomeListRecyAdapter;
import com.lc.hongtai.adapter.IconAdapter;
import com.lc.hongtai.conn.JsonAccessToken;
import com.lc.hongtai.conn.JsonIndex;
import com.lc.hongtai.toast.LovelyToast;
import com.lc.hongtai.view.MarqueeView;
import com.lc.hongtai.view.ProgressBar;
import com.zcx.helper.activity.AppV4Fragment;
import com.zcx.helper.bound.BoundView;
import com.zcx.helper.bound.BoundViewHelper;
import com.zcx.helper.http.AsyCallBack;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import in.srain.cube.views.ptr.PtrClassicDefaultHeader;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import in.srain.cube.views.ptr.PtrUIHandler;
import in.srain.cube.views.ptr.indicator.PtrIndicator;

/**
 * A simple {@link Fragment} subclass.
 */
public class FirstFragment extends AppV4Fragment implements View.OnClickListener, ScrollView.OnTouchListener {
    public final static String FLAG = "IsTiro";

    @Bind(R.id.iv_mailer)
    ImageView ivMailer;
    @Bind(R.id.ll_01)
    LinearLayout ll01;
    @Bind(R.id.ll_02)
    LinearLayout ll02;
    @Bind(R.id.convenientBanner)
    ConvenientBanner convenientBanner;
    //下边banner图片
   /* @Bind(R.id.convenientBanner_middle)
    ConvenientBanner convenientBanner_middle;*/
/*    @Bind(R.id.lv_home_list)
    AdaptListView lv_home_list;*/
    @Bind(R.id.news_xinshou)
    LinearLayout news_xinshou;

    private LinearLayoutManager layoutManager;
    private List<JsonIndex.Info.Borrow_list> menuListContent = new ArrayList<>();

    private HomeListRecyAdapter homeListAdapter;

    private String news_id;

    private OnDataTransmissionListener mListener;

    private MarqueeView verticalSwitchTextView1;


    public static List<String> noticeList = new ArrayList<>();


    List<String> mDatas;
    IconAdapter mAdapter;

    List<JsonIndex.Info.notice> list_notice = new ArrayList<>();


    @Bind(R.id.store_house_ptr_frame)
    PtrFrameLayout store_house_ptr_frame;
    private PtrClassicDefaultHeader header;

    @Bind(R.id.scroll_layout)
    ScrollView scroll_layout;

    //
    @Bind(R.id.lv_home_list)
    RecyclerView lv_home_list;

    //判断Scrollview是否滑动
    private int y;

    //中间图片的url


    @BoundView(R.id.progress_horizontal)
    ProgressBar progress_horizontal;


    LinearLayoutManager linearLayoutManager;

    Dialog dia;
    private TextView tv_progress;
//新手注册

    @BoundView(R.id.layout_recommend)
    private LinearLayout layout_recommend;

    //新手区的投资年限
    @BoundView(R.id.tv_home_list_title)
    private TextView tv_home_list_title;

    @BoundView(R.id.tv_home_list_desc)
    private TextView tv_home_list_desc;
    //年化利率
    @BoundView(R.id.text_rate)
    private TextView text_rate;

    public FirstFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
      //  StatusbarUtils.enableTranslucentStatusbar(getActivity());
        View view = BoundViewHelper.boundView(this, MyApplication.scaleScreenHelper.loadView((ViewGroup) inflater.inflate(R.layout.fragment_first, null)));
        ButterKnife.bind(this, view);
        lv_home_list.setFocusable(false);


        verticalSwitchTextView1 = (MarqueeView) view.findViewById(R.id.marqueeView);
        progress_horizontal.setProgress2(30);
        linearLayoutManager = new LinearLayoutManager(getActivity());
        lv_home_list.setLayoutManager(linearLayoutManager);

        homeListAdapter = new HomeListRecyAdapter(getContext(), menuListContent);
        lv_home_list.setNestedScrollingEnabled(false);
        lv_home_list.setAdapter(homeListAdapter);

        header = new PtrClassicDefaultHeader(getActivity());

        header = new PtrClassicDefaultHeader(getActivity());
        store_house_ptr_frame.setHeaderView(header);

        //调出dialog
        tv_progress = (TextView) view.findViewById(R.id.tv_progress);
        tv_progress.setOnClickListener(this);
        mDatas = new ArrayList<String>();
        for (int i = 'A'; i < 'z'; i++) {
            mDatas.add("" + (char) i);
        }
        layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);


        initListener();
        getAccessToken();
        initLinstener2();


        return view;
    }


    private void initLinstener2() {


        store_house_ptr_frame.setPtrHandler(new PtrHandler() {


            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                //      int firstVisibleItemPosition = ((LinearLayoutManager) mLayoutManager).findFirstCompletelyVisibletemPosition();

                if (y == 0) {
                    return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
                } else {
                    return false;
                }


                //return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);


            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                //  UtilToast.show(getContext(), "刷新开始");


                getAccessToken();


            }
        });
        store_house_ptr_frame.addPtrUIHandler(new PtrUIHandler() {
            @Override
            public void onUIReset(PtrFrameLayout frame) {
                header.onUIReset(frame);
            }

            @Override
            public void onUIRefreshPrepare(PtrFrameLayout frame) {
                header.onUIRefreshPrepare(frame);
            }

            @Override
            public void onUIRefreshBegin(PtrFrameLayout frame) {
                header.onUIRefreshBegin(frame);
            }

            @Override
            public void onUIRefreshComplete(PtrFrameLayout frame) {
                header.onUIRefreshComplete(frame);
            }

            @Override
            public void onUIPositionChange(PtrFrameLayout frame, boolean isUnderTouch, byte status, PtrIndicator ptrIndicator) {
                header.onUIPositionChange(frame, isUnderTouch, status, ptrIndicator);
            }
        });
    }


    private void getAccessToken() {
        new JsonAccessToken("index/index", new AsyCallBack<JsonAccessToken.Info>() {
            @Override
            public void onSuccess(String toast, int type, JsonAccessToken.Info info) throws Exception {
                if (info != null) {
                    if (!TextUtils.isEmpty(info.access_token)) {
                        initData(info.access_token);
                    } else {
                        // UtilToast.show(getActivity(), "安全验证失败！");
                        LovelyToast.makeText(getActivity(), "安全验证失败！", 0, LovelyToast
                                .SUCCESS, LovelyToast.SCALE);
                    }
                }
            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
                //  UtilToast.show(getActivity(), "安全验证失败！");
                LovelyToast.makeText(getActivity(), "安全验证失败！", 0, LovelyToast
                        .SUCCESS, LovelyToast.SCALE);
            }
        }).execute(getActivity(), false);
    }

    private void initData(String access_token) {
        new JsonIndex(access_token, new AsyCallBack<JsonIndex.Info>() {
            @Override
            public void onSuccess(String toast, int type, final JsonIndex.Info info) throws Exception {

                if (info != null) {
                    menuListContent.clear();
                    menuListContent.addAll(info.menu);
                    homeListAdapter.notifyDataSetChanged();


                    news_id = info.news_id;
                    list_notice.addAll(info.news);
                    convenientBanner.setPages(
                            new CBViewHolderCreator<LocalImageHolderView>() {
                                @Override
                                public LocalImageHolderView createHolder() {
                                    return new LocalImageHolderView();
                                }
                            }, info.banner).setPageIndicator(new int[]{R.mipmap.ic_dots_uncheck, R.mipmap.ic_dots_check})
                            //设置指示器的方向
                            .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL).setCanLoop(true);
                    for (int i = 0; i < info.news.size(); i++) {
                        noticeList.add(info.news.get(i).title);
                    }
//                    verticalSwitchTextView1.startWithList(noticeList);
                    verticalSwitchTextView1.startWithList(noticeList);
                    verticalSwitchTextView1.setOnItemClickListener(new MarqueeView.OnItemClickListener() {
                        @Override
                        public void onItemClick(int position, TextView textView) {
                            Intent intent = new Intent();
                            intent.putExtra("title", noticeList.get(position));
                            intent.putExtra("url", "http://vhost602.zihaistar.com/api/index/article_content?id=" + info.news.get(position).id + "&show_type=article");
                            intent.setClass(getActivity(), AdvertisingActivity.class);

                            startActivity(intent);
                        }
                    });


                    //新手的年化利率
                    tv_home_list_title.setText("期限" + info.xs_menu.get(0).borrow_duration + info.xs_menu.get(0).borrow_duration_cn);
                    //新手的起投金额
                    tv_home_list_desc.setText("起投金额" + info.xs_menu.get(0).borrow_min);
                    //年化利率
                    text_rate.setText(info.xs_menu.get(0).borrow_interest_rate + "%");

                    progress_horizontal.setProgress(Double.valueOf(info.xs_menu.get(0).progress));
                    tv_progress.setText(info.xs_menu.get(0).progress + "%");

                }

            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                store_house_ptr_frame.refreshComplete();

            }

        }).execute(getActivity(), false);
    }

    private void initListener() {
        ll01.setOnClickListener(this);
        ll02.setOnClickListener(this);
        ivMailer.setOnClickListener(this);
        news_xinshou.setOnClickListener(this);
        scroll_layout.setOnTouchListener(this);
//新手注册dialog
        layout_recommend.setOnClickListener(this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_01:

                startActivity(new Intent(getActivity(), InvestListActivity.class));

                break;
            case R.id.ll_02:

                startActivity(new Intent(getActivity(), BorrowNextActivity.class));
                break;

            case R.id.iv_mailer:

                Intent intent = new Intent();
           //     intent.putExtra("id", news_id);
                Log.d(news_id,"88888888888888888");

                intent.setClass(getActivity(), NewsActivity.class);
                startActivity(intent);
                break;
            case R.id.news_xinshou:

                Intent intent2 = new Intent();
                intent2.putExtra(FLAG, true);
                intent2.setClass(getActivity(), NewsInvestActivity.class);
                startActivity(intent2);
                break;

            //调出dialog
            case R.id.tv_progress:
                Context context = getContext();
                dia = new Dialog(context, R.style.edit_AlertDialog_style);
                //  dia.setContentView(R.layout.activity_start_dialog);
                dia.setContentView(MyApplication.scaleScreenHelper.loadView((ViewGroup) LayoutInflater.from(getActivity()).inflate(R.layout.activity_start_dialog, null)));
                ImageView mClose_btn = (ImageView) dia.findViewById(R.id.btn_close);
                mClose_btn.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        dia.cancel();// 关闭弹出框
                    }
                });

              /*  Button btn_start = (Button) dia.findViewById(R.id.btn_start);
                btn_start.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                    //    startActivity(new Intent(getActivity(), NewsActivity.class));
                    }
                });
*/
                dia.show();

                dia.setCanceledOnTouchOutside(false); // Sets whether this dialog is

                Window w = dia.getWindow();
                WindowManager.LayoutParams lp = w.getAttributes();
                lp.x = 0;
                lp.y = 40;
                dia.onWindowAttributesChanged(lp);
                break;

            //新手注册dialog
            case R.id.layout_recommend:
                Context context2 = getContext();
                dia = new Dialog(context2, R.style.edit_AlertDialog_style);
                //  dia.setContentView(R.layout.activity_start_dialog);
                dia.setContentView(MyApplication.scaleScreenHelper.loadView((ViewGroup) LayoutInflater.from(getActivity()).inflate(R.layout.activity_novice_dialog, null)));
                ImageView mClose_btn2 = (ImageView) dia.findViewById(R.id.btn_close);
                mClose_btn2.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        dia.cancel();// 关闭弹出框
                    }
                });
                dia.show();
                dia.setCanceledOnTouchOutside(false); // Sets whether this dialog is
                // canceled when touched outside
                // the window's bounds.
                Window window = dia.getWindow();
                WindowManager.LayoutParams layoutParams = window.getAttributes();
                dia.onWindowAttributesChanged(layoutParams);

                break;

        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        y = v.getScrollY();

        return false;
    }

    public class LocalImageHolderView implements Holder<JsonIndex.Info.BannerListContent> {
        private SimpleDraweeView imageView;

        @Override
        public View createView(Context context) {
            imageView = new SimpleDraweeView(context);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, final int position, final JsonIndex.Info.BannerListContent listContent) {
            imageView.setImageURI(Uri.parse(listContent.img));
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.putExtra("title", listContent.title);
                    intent.putExtra("url", listContent.url);
                    /*intent.putExtra("url", listContent.url);

                    Log.d(listContent.url, "88888888888888888888888888");*/
                    intent.setClass(getActivity(), AdvertisingActivity.class);
                    getActivity().startActivity(intent);
                }
            });
        }
    }


    public class LocalImageHolderViewMiddle implements Holder<JsonIndex.Info.BannerMiddle> {
        private SimpleDraweeView imageView;

        @Override
        public View createView(Context context) {
            imageView = new SimpleDraweeView(context);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, final int position, final JsonIndex.Info.BannerMiddle listContent) {
            imageView.setImageURI(Uri.parse(listContent.img));
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.putExtra("title", listContent.title);
                    intent.putExtra("url", listContent.url);

                    Log.d(listContent.url, "88888888888888888888888888");
                    intent.setClass(getActivity(), AdvertisingActivity.class);
                    getActivity().startActivity(intent);
                }
            });


        }
    }


    // 开始自动翻页
    @Override
    public void onResume() {
        super.onResume();
        //开始自动翻页
        convenientBanner.startTurning(3000);
    }

    // 停止自动翻页
    @Override
    public void onPause() {
        super.onPause();
        //停止翻页
        convenientBanner.stopTurning();
    }

    //接口回调的方法
    public interface OnDataTransmissionListener {
        public void dataTransmission(String data);
    }

    public void setOnDataTransmissionListener(OnDataTransmissionListener mListener) {
        this.mListener = mListener;
    }
}
